package cn.zhoushengdao.bingwallpaper

import android.app.WallpaperManager
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.net.URL

class WallpaperUpdateWorker(
    context: Context, params: WorkerParameters
) : CoroutineWorker(context, params) {

    private val repository by lazy { WallpaperRepository(context, AppData(context)) }
    private val data by lazy { AppData(context) }
    private val wallpaperManager by lazy { WallpaperManager.getInstance(context) }

    override suspend fun doWork(): Result {
        return try {
            val wallpapers = repository.fetchWallpapers()
            data.setWallpapers(wallpapers)
            if (data.autoChangeEnabled.first()) {
                setLatestWallpaper(wallpapers.first())
            }
            repository.scheduleDailyUpdate()

            Result.success()
        } catch (e: Exception) {
            Result.retry()
        }
    }

    private suspend fun setLatestWallpaper(wallpaper: WallpaperData) {
        withContext(Dispatchers.IO) {
            val metrics = applicationContext.resources.displayMetrics
            val fullUrl = wallpaper.getFullImageUrl(metrics.widthPixels, metrics.heightPixels)

            URL(fullUrl).openStream().use { wallpaperManager.setStream(it) }

            data.setCurrentWallpaperUrl(wallpaper.imageUrl)
        }
    }
}